package com.sweet.store;

import io.vertx.core.Future;
import io.vertx.core.Vertx;
import org.mapdb.DB;
import org.mapdb.DBMaker;

import javax.swing.plaf.basic.BasicFormattedTextFieldUI;
import java.io.File;
import java.util.Map;

/**
 * Created by sweet on 2019/2/13.
 * ---------------------------
 */
public class MessageStore implements ITransaction {
  private static final MessageStore MESSAGE_STORE = new MessageStore();

  private static final String BASE_PATH = "db/";
  private static final String MESSAGE_DB_PATH = BASE_PATH + "message.db";
  private static final DB MESSAGE_DB = DBMaker.newFileDB(new File(MESSAGE_DB_PATH)).closeOnJvmShutdown().make();

  private static final Map<String, String> MESSAGE_MAP = MESSAGE_DB.getTreeMap("message-map");
  private static final Map<String, String> CLIENT_ACK_MAP = MESSAGE_DB.getTreeMap("client-ack-message-map");
  private static final Map<String, String> SERVER_ACK_MAP = MESSAGE_DB.getTreeMap("server-ack-message-map");

  public static MessageStore instance() {
    return MESSAGE_STORE;
  }

  /**
   * 保存消息
   *
   * @param id    消息ID
   * @param json  消息内容
   * @param vertx
   * @return future
   */
  public Future<Void> save(String id, String json, Vertx vertx) {
    Future<Void> future = Future.future();
    vertx.executeBlocking(f -> {
      MESSAGE_MAP.put(id, json);
      f.complete();
    }, future);
    return future;
  }

  public Future<Boolean> containsMessage(String messageId, Vertx vertx) {
    Future<Boolean> future = Future.future();
    vertx.executeBlocking(f -> f.complete(MESSAGE_MAP.containsKey(messageId)), future);
    return future;
  }



  @Override
  public void commit() {
    MESSAGE_DB.commit();
  }

  @Override
  public void close() {
    commit();
    MESSAGE_DB.close();
  }

}
